<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Resize the width of a text box to fit its content automatically</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
    </head>
    <body>
        <div style="align-items: center; display: flex; justify-content: center">
            <div style="margin: 3rem 0; width: 16rem">
                <input type="text" id="textbox" style="border: 1px solid #cbd5e0; min-width: 40px; padding: 0.5rem" />
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const textboxEle = document.getElementById('textbox');

                // Get the styles
                const styles = window.getComputedStyle(textboxEle);

                // Create a div element
                const fakeEle = document.createElement('div');
                fakeEle.style.position = 'absolute';
                fakeEle.style.top = '0';
                fakeEle.style.left = '-9999px';
                fakeEle.style.overflow = 'hidden';
                fakeEle.style.visibility = 'hidden';
                fakeEle.style.whiteSpace = 'nowrap';
                fakeEle.style.height = '0';

                // Copy font styles from the textbox
                fakeEle.style.fontFamily = styles.fontFamily;
                fakeEle.style.fontSize = styles.fontSize;
                fakeEle.style.fontStyle = styles.fontStyle;
                fakeEle.style.fontWeight = styles.fontWeight;
                fakeEle.style.letterSpacing = styles.letterSpacing;
                fakeEle.style.textTransform = styles.textTransform;

                fakeEle.style.borderLeftWidth = styles.borderLeftWidth;
                fakeEle.style.borderRightWidth = styles.borderRightWidth;
                fakeEle.style.paddingLeft = styles.paddingLeft;
                fakeEle.style.paddingRight = styles.paddingRight;

                document.body.appendChild(fakeEle);

                const setWidth = function () {
                    const string = textboxEle.value || textboxEle.getAttribute('placeholder') || '';
                    fakeEle.innerHTML = string.replace(/\s/g, '&nbsp;');

                    const fakeEleStyles = window.getComputedStyle(fakeEle);
                    textboxEle.style.width = fakeEleStyles.width;
                };

                setWidth();

                textboxEle.addEventListener('input', function (e) {
                    setWidth();
                });
            });
        </script>
    </body>
</html>
